package com.ydj.framework.mysql;

import com.baomidou.mybatisplus.core.conditions.ISqlSegment;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlKeyword;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.google.common.primitives.Ints;
import org.apache.commons.lang3.StringUtils;

import static com.baomidou.mybatisplus.core.enums.SqlKeyword.*;

public class ExtLambdaQueryWrapper<T> extends LambdaQueryWrapper<T> {
    private class OrderByWithFieldSqlSegment implements ISqlSegment {
        private String sql;
        OrderByWithFieldSqlSegment(SFunction<T, ?> column, int[] field) {
            sql = "field(" + columnToString(column) + "," + Ints.join(",", field) + ")";
        }
        OrderByWithFieldSqlSegment(SFunction<T, ?> column, String[] field) {
            sql = "field(" + columnToString(column) + "," + StringUtils.join(",", field) + ")";
        }
        @Override
        public String getSqlSegment() {
            return sql;
        }
    }
    LambdaQueryWrapper<T> eq(boolean condition, String column, Object val) {
        return addCondition(condition, column, EQ, val);
    }

    protected LambdaQueryWrapper<T> addCondition(boolean condition, String column, SqlKeyword sqlKeyword, Object val) {
        return doIt(condition, () -> column, sqlKeyword, () -> formatSql("{0}", val));
    }

    public LambdaQueryWrapper<T> orderByWithField(boolean condition, boolean isAsc, SFunction<T, ?> column, int[] field) {
        SqlKeyword mode = isAsc ? ASC : DESC;
        OrderByWithFieldSqlSegment orderByField = new OrderByWithFieldSqlSegment(column, field);
        return doIt(condition, ORDER_BY, orderByField, mode);
    }

    public LambdaQueryWrapper<T> orderByWithField(boolean condition, boolean isAsc, SFunction<T, ?> column, String[] field) {
        SqlKeyword mode = isAsc ? ASC : DESC;
        OrderByWithFieldSqlSegment orderByField = new OrderByWithFieldSqlSegment(column, field);
        return doIt(condition, ORDER_BY, orderByField, mode);
    }

    public String columnToString(SFunction<T, ?> column) {
        return super.columnToString(column);
    }

    public String formatObject(Object val) {
        return super.formatSql("{0}", val);
    }
}